package com.mybatis_puls.demo.controller;


import cn.hutool.core.util.IdUtil;
import com.mybatis_puls.demo.entity.FileS;
import com.mybatis_puls.demo.entity.OrderS;
import com.mybatis_puls.demo.entity.R;
import com.mybatis_puls.demo.entity.User;
import com.mybatis_puls.demo.service.FileService;
import com.mybatis_puls.demo.service.OrderSService;
import com.mybatis_puls.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 小🌤
 * @since 2021-01-03
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    private OrderSService orderSService;
    @Autowired
    private FileService fileService;
    @Autowired

    private UserService userService;
    String newFileName = null;

    /**
     * 打印服务得的保存
     *
     * @param
     * @param files
     * @param orderS
     * @return
     * @throws IOException
     */
    @RequestMapping("/updolad")
    public Object UPploads(FileS files, OrderS orderS) throws IOException {

        try {
            List<User> users = userService.listByIds(Collections.singleton(files.getUserId()));
            if(users.size()>0){
                User user = users.get(0);
                if(user.getShowFee()>orderS.getMoney()){
                    user.setShowFee(user.getShowFee()-orderS.getMoney());
                    userService.updateById(user);
                    files.setUuid(IdUtil.simpleUUID());
                    files.setFileName(newFileName);
                    fileService.save(files);
                    orderS.setUuid(files.getUuid());
                    orderS.setDetailId(files.getId());
                    orderS.setTime(new Date());
                    orderSService.save(orderS);
                    newFileName=null;
                }else {
                    return new R().setCode(400);
                }
            }

        } catch (IllegalStateException e) {
            return new R().setCode(400);
        }
        return new R();
    }

    /**
     * 文件上传
     * @param file
     * @return
     */
    @RequestMapping("/updoladfile")
    public Object UPpload(MultipartFile file) {
        if (file != null) {
            String originalFilename = file.getOriginalFilename();
            // *只有当满足图片格式时才进来，重新赋图片名，防止出现名称重复的情况
            newFileName = originalFilename;
            // 该方法返回的为当前项目的工作目录，即在哪个地方启动的java线程
            String dirPath = System.getProperty("user.dir");
            String path = File.separator + "src/main/resources/static/images/files/" + File.separator + newFileName;
            File destFile = new File(dirPath + path);
         newFileName="/images/files/"+newFileName;
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            try {
                file.transferTo(destFile);
                // *将相对路径返回给前端
            } catch (IOException e) {
                return new R().setCode(400);
            }

        }

        return new R();
    }



    /**
     * 下载文件
     * @param response
     * @return 成功下载文件，失败返回0
     * @throws IOException
     */
    @RequestMapping("/download.do")
    public Object downloadFileS(String fileName,HttpServletResponse response) throws IOException, IOException {
        // 该方法返回的为当前项目的工作目录，即在哪个地方启动的java线程
        String dirPath = System.getProperty("user.dir");
        String path = dirPath + "\\src\\main\\resources\\static\\images\\files\\"+fileName;
        File file = new File(path);
        if(!file.exists()){
            return new R().setCode(400);//文件不存在就退出方法
        }

        FileInputStream fileInputStream = new FileInputStream(file);
        //设置Http响应头告诉浏览器下载这个附件,下载的文件名也是在这里设置的
        response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[2048];
        int len = 0;
        while ((len = fileInputStream.read(bytes))>0){
            outputStream.write(bytes,0,len);
        }
        fileInputStream.close();
        outputStream.close();


        return new R();
    }
}